package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.model.Instance;
import com.ezjie.ielts.model.Mean;
import com.ezjie.ielts.model.ReviewToWordData;
import com.ezjie.ielts.model.StudyRecord;
import com.ezjie.ielts.model.WordBean;
import com.ezjie.ielts.module_word.adapter.ExampleSentenceAdapter;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PlayAnimationUtils;
import com.ezjie.ielts.util.PreferencesUtil;
import com.ezjie.ielts.util.SpeechTTSUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.stikkyheader.StikkyHeaderBuilder;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

public class WordParaphraseFragment extends Fragment implements OnClickListener {

	private Context mContext;
	private ScrollView exp_sv;
	private TextView word, tv_explaneHint;
	private TextView soundmark;// 音标
	private ListView example_sentence;// 例句
	private List<Instance> mInstances;
	private ExampleSentenceAdapter mSentenceAdapter;
	private View sentence_ll;

	private LinearLayout play_ll;
	// private StudyRoundProgressBar voice_seek_bar;
	// private ProgressBar pb_progress;
	private Button ok;
	// private ImageView backBtn;//返回按钮
	// private TextView navi_title_text;
	private int index, total, progress;// 该题下标，总的题数

	private WordBean mBean;
	private TextView meaning;
	private List<Mean> mMean;

	private ImageView play;// 播放单词
	private AnimationDrawable animation;
	private AnimationDrawable animation2;

	private boolean isPause = true;// 判断是暂停还是完成练习
	private String wgid, status;
	private List<StudyRecord> studyRecords;
	private ReviewToWordData data;

	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = getActivity();
		mMean = new ArrayList<Mean>();
		mInstances = new ArrayList<Instance>();
		SpeechTTSUtil.getInstance(getActivity()).init();
		animation = PlayAnimationUtils.PlayWordAnimation(getActivity());
		animation2 = PlayAnimationUtils.PlayWordAnimation(getActivity());
		studyRecords = new ArrayList<StudyRecord>();
		mWordTask = new WordTask(mContext);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.word_paraphrase, null);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		initData();
		setView();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		StikkyHeaderBuilder.stickTo(exp_sv).setHeader(R.id.ciyi_ll, (FrameLayout) getView()).minHeightHeader(0).build();
	}

	private void setView() {
		ok.setOnClickListener(this);
		play.setOnClickListener(this);
		play_ll.setOnClickListener(this);
		example_sentence.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				ImageView playImg = (ImageView) view.findViewById(R.id.play_img);
				if (animation2 != null && animation2.isRunning()) {
					animation2.selectDrawable(0);
					animation2.stop();
				}
				animation2 = PlayAnimationUtils.PlayWordAnimation(getActivity());
				playImg.setImageDrawable(animation2);
				animation2.start();
				String sentence_text = mInstances.get(position).getOrigin();
				if (!TextUtils.isEmpty(sentence_text)) {
					SpeechTTSUtil.getInstance(getActivity()).speak(sentence_text, animation2);
				}
			}
		});
	}

	private void initView(View view) {
		play = (ImageView) view.findViewById(R.id.play);
		word = (TextView) view.findViewById(R.id.word);
		soundmark = (TextView) view.findViewById(R.id.soundmark);
		sentence_ll = view.findViewById(R.id.sentence_ll);
		example_sentence = (ListView) view.findViewById(R.id.example_sentence);
		ok = (Button) view.findViewById(R.id.ok);
		meaning = (TextView) view.findViewById(R.id.meaning_words);
		exp_sv = (ScrollView) view.findViewById(R.id.exp_sv);
		exp_sv.smoothScrollTo(0, 0);
		play_ll = (LinearLayout) view.findViewById(R.id.ciyi_ll);
		tv_explaneHint = (TextView) view.findViewById(R.id.tv_explane_hint);
	}

	private void initData() {
		YsApplication mApplication = (YsApplication) getActivity().getApplication();
		mBean = mApplication.getWordBean();
		studyRecords = mApplication.getStudyRecords();
		data = mApplication.getReviewToWordData();

		tv_explaneHint.setFocusable(true);
		tv_explaneHint.setFocusableInTouchMode(true);
		tv_explaneHint.requestFocus();

		total = data.getTotal();
		progress = data.getProgress();
		word.setText(Html.fromHtml(data.getWordString()));
		if (!TextUtils.isEmpty(data.getSoundmarkString()) && !"[]".equals(data.getSoundmarkString())) {
			sentence_ll.setVisibility(View.VISIBLE);
			soundmark.setText(Html.fromHtml(data.getSoundmarkString()));
		} else {
			sentence_ll.setVisibility(View.INVISIBLE);
		}
		wgid = data.getWgid();
		status = data.getStatus();
		index = data.getCurrentPosition();
		mMean = mBean.getMeans();
		mInstances = mBean.getInstances();

		mSentenceAdapter = new ExampleSentenceAdapter(mContext);
		mSentenceAdapter.setList(mInstances, word.getText().toString());
		example_sentence.setAdapter(mSentenceAdapter);
		initParentProgress();
		meaning.setText(Html.fromHtml(ListUtils.getTransferStrByList(mMean)));
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (!hidden) {
			// 每次切换界面的时候 都重新获得数据
			initData();
		}
	}

	private void initParentProgress() {
		// 控制父view显示进度
		Activity parentActivity = getActivity();
		if (parentActivity instanceof ReviewStudyManagerActivity) {
			ReviewStudyManagerActivity activity = (ReviewStudyManagerActivity) parentActivity;
			activity.showProgress(total, progress);
		}
	}

	private void changeView() {
		// 控制父view显示详情
		Activity parentActivity = getActivity();
		if (parentActivity instanceof ReviewStudyManagerActivity) {
			ReviewStudyManagerActivity activity = (ReviewStudyManagerActivity) parentActivity;
			activity.showView(ReviewStudyManagerActivity.SHOW_WORD);
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SpeechTTSUtil.getInstance(getActivity()).close();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_PARAPHRASE);
		MobclickAgent.onPause(mContext);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_PARAPHRASE);
		MobclickAgent.onResume(mContext);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.navi_back_btn:
			onBackPressed();
			break;
		case R.id.ok:
			SpeechTTSUtil.getInstance(getActivity()).pause();
			if (animation2 != null) {
				animation2.selectDrawable(0);
				animation2.stop();
			}
			changeView();
			break;
		case R.id.play:
		case R.id.ciyi_ll:
			if (animation2 != null && animation2.isRunning()) {
				animation2.selectDrawable(0);
				animation2.stop();
			}
			play.setImageDrawable(animation);
			animation.start();
			String text = word.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				SpeechTTSUtil.getInstance(getActivity()).speak(text, animation);
			}
			break;
		}
	}

	public void onBackPressed() {
		if (getActivity() != null) {
			View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_rob_warn_dialog, null);
			final Dialog dialog = new Dialog(getActivity(), R.style.customDialog);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setContentView(view);
			dialog.show();

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			tv_content.setText(R.string.word_first_exit_msg);
			LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
			LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);

			Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
			Button btn_no = (Button) view.findViewById(R.id.btn_no);
			btn_no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
					}
				}
			});
			btn_yes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 友盟统计
					MobclickAgent.onEvent(getActivity(), "word_review_backBtn");
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
						isPause = true;
						// 保存进度
						saveProgress(wgid, status, isPause);
						if (isPause) {
							PreferencesUtil.putString(mContext, "temp_status", "1");
							PreferencesUtil.putInt(mContext, "finish_num", progress);
						} else {
							PreferencesUtil.putString(mContext, "temp_status", "2");
							PreferencesUtil.putInt(mContext, "finish_num", progress);
						}
					}
				}
			});
		}
	}

	/**
	 * 保存进度 更改单词状态
	 */
	private void saveProgress(String wgid, String status, boolean isPause) {

		if (getActivity() != null) {
			if (!NetworkUtil.isNetworkAvailable(getActivity())) {
				AppUtil.showToast(getActivity(), R.string.no_network);
				return;
			}

			mWordTask.saveProgress(wgid + "", isPause + "", status + "", JSON.toJSONString(studyRecords),
					new HttpRequestAbstractCallBack(mContext,true) {
						@Override
						public void onStartCallBack() {
							super.onStartCallBack();
							AppUtil.showProgressDialog(getActivity());
						}

						@Override
						public void onSuccessCallBack(String result) {
							super.onSuccessCallBack(result);
							LogUtils.d(result);
							AppUtil.dismissProgressDialog();
							try {
								BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
								if (baseBean != null && 200 == baseBean.getStatus_code()) {
									// 提交成功
									if (getActivity() != null) {
										Intent intent = new Intent(mContext, ReviewSummaryFragment.class);
										intent.putExtra("isOver", true);
										getActivity().setResult(666, intent);
										getActivity().finish();
										getActivity().overridePendingTransition(R.anim.open_from_right,
												R.anim.open_to_left);
									}
								} else {
									if (getActivity() != null) {
										AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
									}
								}
							} catch (Exception e) {
								LogUtils.d("json数据异常");
								LogUtils.exception(e);
							}
						}

						@Override
						public void onFailureCallBack(HttpException error, String msg) {
							super.onFailureCallBack(error, msg);
							LogUtils.e(msg);
							AppUtil.dismissProgressDialog();
							AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
						}
					});
		}
	}

}
